#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author： 青城子
# datetime： 2022/2/26 16:10 
# ide： PyCharm

import time
import os
import re

import uiautomator2 as u2

from conf import settings
from utils.loghandler import logger

serials = ""


def get_devices_list(serial):
    global serials
    serials = serial


class PublicOperation:
    """
    操作安卓app&设备父类
    """

    def __init__(self):
        self.devices_no = settings.DEVICES_NUMBER
        self.driver_ip = settings.DEVICES_IP
        self.pack_name = settings.APP_PACKAGE
        self.apk_path = settings.APK_PATH
        self.img_time = time.strftime("%Y-%m-%d %H_%M_%S")  # 生成截图片已当前时间命名图片名称
        self.directory_time = time.strftime("%Y-%m-%d")  # 当日截图目录名称
        self.root_directory = settings.BASE_DIR  # 项目根目录
        self.screen_dir = settings.DIR_PATH_DICT.get("screenshots")
        if re.search(r"^\d+\.", serials):
            self.devices = u2.connect_adb_wifi(serials)
        else:
            self.devices = u2.connect_usb(serials)
        self.in_the_home() # 屏幕是息屏状态就打开
        self.size = self.devices.window_size()  # 移动设备屏幕尺寸

    def install_app(self):
        """
        安装app
        :return:
        """
        self.devices.app_install(self.apk_path)

    def uninstall_app(self):
        """
        卸载app
        :return:
        """
        self.devices.app_uninstall(package_name=self.pack_name)

    def quit_app(self):
        """
        测试用例执行完毕，恢复app初始化
        :return:
        """
        self.devices.watcher.stop()  # 关闭监控器线程
        self.devices.app_stop(package_name=self.pack_name)  # 退出app
        self.devices.app_clear(package_name=self.pack_name)  # 清除app全部缓存数据

    def create_screens_hot_dir(self, *args):
        # 创建截图一级目录
        try:
            if os.path.exists(self.screen_dir):  # 截图的目录screenshots是否存在
                pass
            else:
                os.mkdir("{0}".format(self.screen_dir))
        except Exception as error:
            logger().info("创建截图目录失败:{0}".format(error))

        # 创建二级目录
        try:
            if os.path.exists(r"{0}\{1}".format(self.screen_dir, self.directory_time)):
                """
                 判断screenshots目录下是否存在(2020-04-15)格式命名的目录
                """
                pass
            else:
                os.mkdir(r"{0}\{1}".format(self.screen_dir, self.directory_time))
        except Exception as error:
            logger().info("创建每日截图目录失败:{0}".format(error))

        # 创建三级目录用于存放用例执行成功时截图
        try:
            if os.path.exists(r"{0}\{1}\{2}".format(self.screen_dir, self.directory_time, "success")):
                pass
            else:
                os.mkdir(r"{0}\{1}\{2}".format(self.screen_dir, self.directory_time, "success"))
        except Exception as error:
            logger().info("创建每日成功截图目录失败:{0}".format(error))
        direct_success = r"{0}\{1}\{2}".format(self.screen_dir, self.directory_time, "success")

        # 创建三级目录，用于保存用例执行失败时截图信息
        if args[0]:
            try:
                if os.path.exists(r"{0}\{1}\{2}".format(self.screen_dir, self.directory_time, "errors")):
                    pass
                else:
                    os.mkdir(r"{0}\{1}\{2}".format(self.screen_dir, self.directory_time, "error"))

            except Exception as error:
                logger().info("每日错误目录失败:{0}".format(error))

        direct_error = r"{0}\{1}\{2}".format(self.screen_dir, self.directory_time, "error")
        return direct_success, direct_error,

    def screenshots(self, type_str=None, error=None):
        """
        截图
        :return:
        """
        dir_success, dir_error = self.create_screens_hot_dir(error)
        # 用例执行成功时页面截图
        if type_str:
            image_page = r"{0}\{1}{2}.png".format(dir_success, type_str, self.img_time)
        else:
            image_page = r"{0}\{1}.png".format(dir_success, self.img_time)

        if error:
            # 代码执行错误时，进行截图
            image_page_error = r"{0}\{1}.png".format(dir_error, self.img_time)
            self.devices.screenshot(image_page_error)
        else:
            self.devices.screenshot(image_page)

    def up_swipe_size(self):
        """
        获取屏幕向上滑动
        :return:
        """
        x1 = int(self.size[0] * 0.5)  # x轴中间
        y1 = int(self.size[1] * 0.85)  # y轴最下面
        y2 = int(self.size[1] * 0.15)  # y轴最上面
        self.devices.swipe(x1, y1, x1, y2)

    def down_swipe_size(self):
        """
        屏幕向下滑动
        :return:
        """
        x1 = int(self.size[0] * 0.5)  # x轴中间
        y1 = int(self.size[1] * 0.85)  # y轴最下面
        y2 = int(self.size[1] * 0.15)  # y轴最上面
        self.devices.swipe(x1, y2, x1, y1)

    def in_the_home(self):
        """
         进入home页面
        :return:
        """
        # 移动设备屏幕状态
        if self.devices.info.get("screenOn"):
            pass
        else:  # 息屏状态
            self.devices.unlock()  # 解锁
